<template>
  <view class="u-page">
    <up-empty
      v-if="messageList.length === 0"
      mode="message"
      text="暂无消息"
      margin-top="200"

    >
    </up-empty>
    <up-list v-if="messageList.length > 0" @scrolltolower="scrolltolower">
      <up-list-item v-for="(item) in messageList" :key="item.id" >
        <up-card
          :title="item.title"
          :thumb="item.icon"
          :sub-title="DateFormat(item.createTime)"
          :full="true"
          :padding="10"
        >
          <template #body>
            <up-parse  :content="item.content"></up-parse>
          </template>
        </up-card>
      </up-list-item>
    </up-list>
  </view>
</template>

<script lang="ts" setup>
import { to } from 'await-to-js';
import useIMStore from '@/store/modules/im';
import { timeFrom ,queryParams} from 'uview-plus';
import {DateFormat} from '@/utils/index';
import { MessageVo } from '@/types/IMMessageDTO';

const imStore = useIMStore();

const messageList = ref([]);

const total=ref(0)
const params = ref({
  messageType: '',
  pageSize:10,
  pageNum:1
});
const scrolltolower = () => {
  if (messageList.value.length < total.value) {
    params.value.pageNum += 1;
    getMessageList();
  }
};
const getMessageList = async () => {
  const res = await uni.$u.http.get(`/system/instantMessaging/messageListByType${queryParams(params.value)}`);
  messageList.value.push(...res.rows)
  total.value=res.total;
};

//实时处理新消息
const realTimeProcess=async (message :MessageVo)=>{
  //将消息加入到列表第一个元素中
  messageList.value.unshift({
    id: message.IMId,
    icon: message.iconUrl,
    title: message.messageTitle,
    content: message.messageInfo,
    createTime: message.sendTime,
  });
  //当有新消息时立马为已读
  const res = await uni.$u.http.get(`/system/instantMessaging/updateReadByType`, { params: { messageType: params.value.messageType } });
  imStore.set(params.value.messageType, 0);


}


onLoad(async (options: any) => {
  params.value.messageType=options.messageType;
  params.value.pageNum=1;
  await getMessageList();
  await uni.pageScrollTo({ scrollTop: 0, duration: 300 });
  if(params.value.messageType){
    uni.$on(params.value.messageType, realTimeProcess);
  }
});
onUnload(()=>{
  if(params.value.messageType){
    uni.$off(params.value.messageType,realTimeProcess)
  }

})
</script>

<style scoped lang="scss">

</style>
